/***************************************************
File:           LPK_SpawnRandomOnEvent.cs
Authors:        Christopher Onorati
Last Updated:   6/10/2019
Last Version:   2018.3.14

Description:
  This component can be attached to any object to cause
  it to spawn a random game object from an array upon
  receiving an event.

This script is a basic and generic implementation of its 
functionality. It is designed for educational purposes and 
aimed at helping beginners.

Copyright 2018-2019, DigiPen Institute of Technology
***************************************************/

using UnityEngine;
using UnityEditor;

namespace LPK
{

/**
* CLASS NAME  : LPK_SpawnRandomOnEvent
* DESCRIPTION : Component to spawn a random game object on events.
**/
public class LPK_SpawnRandomOnEvent : LPK_SpawnOnEvent
{
    /************************************************************************************/

    [Tooltip("Prefabs to possibly spawn upon receiving an event.  You can use the same prefab multiple times to make it more likely to be selected.")]
    [Rename("Prefab Options")]
    public GameObject[] m_pOptionsToSpawn;

    /**
    * FUNCTION NAME: SpawnGameObject
    * DESCRIPTION  : Spawn the desired object.  Public so the Unity UI system can interact with this function.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    override public void SpawnGameObject()
    {
        //Array length 0, no choices.
        if(m_pOptionsToSpawn.Length < 1)
        {
            if(m_bPrintDebug)
                LPK_PrintDebug(this, "No objects set to be options for spawning.  Please set objects to choose from for spawning.");

            return;
        }

        //Spawn the objects
        for (int i = 0; i < m_iSpawnPerEventCount; ++i)
        {
            if (m_iMaxTotalSpawnCount == 0 || m_iSpawnCount < m_iMaxTotalSpawnCount)
            {
                //Too many alive objects, but still count the spawn.
                //NOTENOTE: If you want failed spawns not to count, remove the increment line below.
                if(m_pActiveList.Count >= m_iMaxAliveAtOnce && m_iMaxAliveAtOnce != 0)
                {
                    m_iSpawnCount++;
                    return;
                }

                float randX = Random.Range(m_vecOffset.x - m_vecRandomOffsetVariance.x, m_vecOffset.x + m_vecRandomOffsetVariance.x);
                float randY = Random.Range(m_vecOffset.y - m_vecRandomOffsetVariance.y, m_vecOffset.y + m_vecRandomOffsetVariance.y);
                float randZ = Random.Range(m_vecOffset.z - m_vecRandomOffsetVariance.z, m_vecOffset.z + m_vecRandomOffsetVariance.z);

                Vector3 randAngles = new Vector3(Random.Range(-m_vecRandomAngleVariance.x, m_vecRandomAngleVariance.x), Random.Range(-m_vecRandomAngleVariance.y, m_vecRandomAngleVariance.y),
                                                 Random.Range(-m_vecRandomAngleVariance.z, m_vecRandomAngleVariance.z));

                GameObject prefabToSpawn = m_pOptionsToSpawn[Random.Range(0, m_pOptionsToSpawn.Length - 1)];

                //NOTENOTE:  If a null object is picked, do not count towards the spawn.  This also terminates the loop to avoid a case of infinite looping.
                if(prefabToSpawn == null)
                {
                    if(m_bPrintDebug)
                        LPK_PrintError(this, "Selected null object to spawn.");

                    break;
                }

                GameObject obj = (GameObject)Instantiate(prefabToSpawn, m_pTargetSpawnTransformObj.position + new Vector3(randX, randY, randZ), Quaternion.identity);
                Transform objTransform = obj.GetComponent<Transform>();

                if (m_bCopyTargetRotation)
                    objTransform.eulerAngles = m_pTargetSpawnTransformObj.eulerAngles + randAngles;
                else
                    objTransform.eulerAngles = randAngles;

                if (m_bAttachToSpawnTarget)
                    objTransform.SetParent(m_pTargetSpawnTransformObj);

                if (m_bAttachToSpawner)
                    objTransform.SetParent(m_cTransform);

                if (!string.IsNullOrEmpty(m_sNewObjectName))
                    obj.name = m_sNewObjectName;

                if (m_bPrintDebug)
                    LPK_PrintDebug(this, "Game object spawned.");

                m_iSpawnCount++;
                m_pActiveList.Add(obj);
            }
        }

        //Dispatch spawn event
        DispatchSpawnEvent();
    }
}

#if UNITY_EDITOR

[CustomEditor(typeof(LPK_SpawnRandomOnEvent))]
public class LPK_SpawnRandomOnEventEditor : Editor
{
    SerializedProperty optionsToSpawn;
    SerializedProperty targetSpawnTransformObj;

    SerializedProperty eventTriggers;

    SerializedProperty spawnObjectReceivers;

    /**
    * FUNCTION NAME: OnEnable
    * DESCRIPTION  : Save out serialized classes.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    void OnEnable()
    {
        optionsToSpawn = serializedObject.FindProperty("m_pOptionsToSpawn");
        targetSpawnTransformObj = serializedObject.FindProperty("m_pTargetSpawnTransformObj");

        eventTriggers = serializedObject.FindProperty("m_EventTrigger");

        spawnObjectReceivers = serializedObject.FindProperty("m_GameObjectSpawnedEvent");
    }

    /**
    * FUNCTION NAME: OnInspectorGUI
    * DESCRIPTION  : Override GUI for inspector.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    public override void OnInspectorGUI()
    {
        LPK_SpawnRandomOnEvent owner = (LPK_SpawnRandomOnEvent)target;

        LPK_SpawnRandomOnEvent editorOwner = owner.GetComponent<LPK_SpawnRandomOnEvent>();

        EditorGUI.BeginDisabledGroup(true);
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.PrefixLabel("Script");
        editorOwner = (LPK_SpawnRandomOnEvent)EditorGUILayout.ObjectField(editorOwner, typeof(LPK_SpawnRandomOnEvent), false);
        GUILayout.EndHorizontal();
        EditorGUI.EndDisabledGroup();

        //Undo saving.
        Undo.RecordObject(owner, "Property changes on LPK_SpawnRandomOnEvent");

        //Component properties.
        GUILayout.Space(10);
        EditorGUILayout.LabelField("Component Properties", EditorStyles.boldLabel);

        EditorGUILayout.PropertyField(optionsToSpawn, true);
        EditorGUILayout.PropertyField(targetSpawnTransformObj, true);
        owner.m_bCopyTargetRotation = EditorGUILayout.Toggle(new GUIContent("Copy Target Rotation", "Whether the rotation of TargetSpawnTransformObj should be copied to the spawned object."), owner.m_bCopyTargetRotation);
        owner.m_sNewObjectName = EditorGUILayout.TextField(new GUIContent("Override Name", "Assign this string to the objects spawned as their name."), owner.m_sNewObjectName);
        owner.m_bAttachToSpawner = EditorGUILayout.Toggle(new GUIContent("Assign Parent Spawner", "Parent the created prefab to the spawner object."), owner.m_bAttachToSpawner);
        owner.m_bAttachToSpawnTarget = EditorGUILayout.Toggle(new GUIContent("Assign Parent Target", "Parent the created prefab to the transform spawn location object."), owner.m_bAttachToSpawnTarget);
        owner.m_iSpawnPerEventCount = EditorGUILayout.IntField(new GUIContent("Spawns Per Event", "How many instances of the archetype to spawn everytime an event is received."), owner.m_iSpawnPerEventCount);
        owner.m_iMaxTotalSpawnCount = EditorGUILayout.IntField(new GUIContent("Max Spawns", "Total maximum number of instances this object is allowed to spawn. (0 means no limit)."), owner.m_iMaxTotalSpawnCount);
        owner.m_iMaxAliveAtOnce = EditorGUILayout.IntField(new GUIContent("Max Alive", "Max amount of objects to have active at once.  (0 means no limit)."), owner.m_iMaxAliveAtOnce);
        owner.m_vecOffset = EditorGUILayout.Vector3Field(new GUIContent("Offset", "Offset from spawn position."), owner.m_vecOffset);
        owner.m_vecRandomOffsetVariance = EditorGUILayout.Vector3Field(new GUIContent("Random Offset Variance", "Random variance applied to the spawn position. A value of (2, 0, 0) will apply a random offset of -2 to 2 to the X value of the spawn position"), owner.m_vecRandomOffsetVariance);
        owner.m_vecRandomAngleVariance = EditorGUILayout.Vector3Field(new GUIContent("Rotational Offset Variance", "Random angular variance applied to the spawned object's angles."), owner.m_vecRandomAngleVariance);
        owner.m_flCooldown = EditorGUILayout.FloatField(new GUIContent("Cooldown", "Amount of time to wait (in seconds) until an event can trigger another spawn."), owner.m_flCooldown);

        //Events
        EditorGUILayout.PropertyField(eventTriggers, true);
        EditorGUILayout.PropertyField(spawnObjectReceivers, true);

        //Debug properties.
        GUILayout.Space(10);
        EditorGUILayout.LabelField("Debug Properties", EditorStyles.boldLabel);

        owner.m_bPrintDebug = EditorGUILayout.Toggle(new GUIContent("Print Debug Info", "Toggle console debug messages."), owner.m_bPrintDebug);
        owner.m_sLabel = EditorGUILayout.TextField(new GUIContent("Label", "Notes for the user about this component.  This does nothing to the game or build."), owner.m_sLabel);

        //Apply changes.
        serializedObject.ApplyModifiedProperties();
    }
}

#endif  //UNITY_EDITOR

}   //LPK
